removing unused globals and some whitespace cleaning
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 var $mRedirectUrl;
40 /**#@-*/
41
42 /**
43 * Constructor and clear the article
44 * @param Title &$title
45 * @param integer $oldId Revision ID, null to fetch from request, zero for current
46 */
47 function Article( &$title, $oldId = null ) {
48 $this->mTitle =& $title;
49 $this->mOldId = $oldId;
50 $this->clear();
51 }
52
53 /**
54 * Tell the page view functions that this view was redirected
55 * from another page on the wiki.
56 * @param Title $from
57 */
58 function setRedirectedFrom( $from ) {
59 $this->mRedirectedFrom = $from;
60 }
61
62 /**
63 * @return mixed false, Title of in-wiki target, or string with URL
64 */
65 function followRedirect() {
66 $text = $this->getContent();
67 $rt = Title::newFromRedirect( $text );
68
69 # process if title object is valid and not special:userlogout
70 if( $rt ) {
71 if( $rt->getInterwiki() != '' ) {
72 if( $rt->isLocal() ) {
73 // Offsite wikis need an HTTP redirect.
74 //
75 // This can be hard to reverse and may produce loops,
76 // so they may be disabled in the site configuration.
77
78 $source = $this->mTitle->getFullURL( 'redirect=no' );
79 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
80 }
81 } else {
82 if( $rt->getNamespace() == NS_SPECIAL ) {
83 // Gotta hand redirects to special pages differently:
84 // Fill the HTTP response "Location" header and ignore
85 // the rest of the page we're on.
86 //
87 // This can be hard to reverse, so they may be disabled.
88
89 if( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) {
90 // rolleyes
91 } else {
92 return $rt->getFullURL();
93 }
94 }
95 return $rt;
96 }
97 }
98
99 // No or invalid redirect
100 return false;
101 }
102
103 /**
104 * get the title object of the article
105 */
106 function getTitle() {
107 return $this->mTitle;
108 }
109
110 /**
111 * Clear the object
112 * @access private
113 */
114 function clear() {
115 $this->mDataLoaded = false;
116 $this->mContentLoaded = false;
117
118 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
119 $this->mRedirectedFrom = null; # Title object if set
120 $this->mUserText =
121 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
122 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
123 $this->mTouched = '19700101000000';
124 $this->mForUpdate = false;
125 $this->mIsRedirect = false;
126 $this->mRevIdFetched = 0;
127 $this->mRedirectUrl = false;
128 }
129
130 /**
131 * Note that getContent/loadContent do not follow redirects anymore.
132 * If you need to fetch redirectable content easily, try
133 * the shortcut in Article::followContent()
134 *
135 * @fixme There are still side-effects in this!
136 * In general, you should use the Revision class, not Article,
137 * to fetch text for purposes other than page views.
138 *
139 * @return Return the text of this revision
140 */
141 function getContent() {
142 global $wgRequest, $wgUser, $wgOut;
143
144 # Get variables from query string :P
145 $action = $wgRequest->getText( 'action', 'view' );
146 $section = $wgRequest->getText( 'section' );
147 $preload = $wgRequest->getText( 'preload' );
148
149 $fname = 'Article::getContent';
150 wfProfileIn( $fname );
151
152 if ( 0 == $this->getID() ) {
153 if ( 'edit' == $action ) {
154 wfProfileOut( $fname );
155
156 # If requested, preload some text.
157 $text=$this->getPreloadedText($preload);
158
159 # We used to put MediaWiki:Newarticletext here if
160 # $text was empty at this point.
161 # This is now shown above the edit box instead.
162 return $text;
163 }
164 wfProfileOut( $fname );
165 $wgOut->setRobotpolicy( 'noindex,nofollow' );
166
167 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
168 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
169 } else {
170 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
171 }
172
173 return "<div class='noarticletext'>$ret</div>";
174 } else {
175 $this->loadContent();
176 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
177 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
178 $wgUser->isIP($this->mTitle->getText()) &&
179 $action=='view'
180 ) {
181 wfProfileOut( $fname );
182 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
183 } else {
184 if($action=='edit') {
185 if($section!='') {
186 if($section=='new') {
187 wfProfileOut( $fname );
188 $text=$this->getPreloadedText($preload);
189 return $text;
190 }
191
192 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
193 # comments to be stripped as well)
194 $rv=$this->getSection($this->mContent,$section);
195 wfProfileOut( $fname );
196 return $rv;
197 }
198 }
199 wfProfileOut( $fname );
200 return $this->mContent;
201 }
202 }
203 }
204
205 /**
206 * Get the contents of a page from its title and remove includeonly tags
207 *
208 * TODO FIXME: This is only here because of the inputbox extension and
209 * should be moved there
210 *
211 * @deprecated
212 *
213 * @param string The title of the page
214 * @return string The contents of the page
215 */
216 function getPreloadedText($preload) {
217 if ( $preload === '' )
218 return '';
219 else {
220 $preloadTitle = Title::newFromText( $preload );
221 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
222 $rev=Revision::newFromTitle($preloadTitle);
223 if ( is_object( $rev ) ) {
224 $text = $rev->getText();
225 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
226 // its own mini-parser! -ævar
227 $text = preg_replace( '~</?includeonly>~', '', $text );
228 return $text;
229 } else
230 return '';
231 }
232 }
233 }
234
235 /**
236 * This function returns the text of a section, specified by a number ($section).
237 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
238 * the first section before any such heading (section 0).
239 *
240 * If a section contains subsections, these are also returned.
241 *
242 * @param string $text text to look in
243 * @param integer $section section number
244 * @return string text of the requested section
245 */
246 function getSection($text,$section) {
247
248 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
249 # comments to be stripped as well)
250 $striparray=array();
251 $parser=new Parser();
252 $parser->mOutputType=OT_WIKI;
253 $parser->mOptions = new ParserOptions();
254 $striptext=$parser->strip($text, $striparray, true);
255
256 # now that we can be sure that no pseudo-sections are in the source,
257 # split it up by section
258 $secs =
259 preg_split(
260 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
261 $striptext, -1,
262 PREG_SPLIT_DELIM_CAPTURE);
263 if($section==0) {
264 $rv=$secs[0];
265 } else {
266 $headline=$secs[$section*2-1];
267 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
268 $hlevel=$matches[1];
269
270 # translate wiki heading into level
271 if(strpos($hlevel,'=')!==false) {
272 $hlevel=strlen($hlevel);
273 }
274
275 $rv=$headline. $secs[$section*2];
276 $count=$section+1;
277
278 $break=false;
279 while(!empty($secs[$count*2-1]) && !$break) {
280
281 $subheadline=$secs[$count*2-1];
282 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
283 $subhlevel=$matches[1];
284 if(strpos($subhlevel,'=')!==false) {
285 $subhlevel=strlen($subhlevel);
286 }
287 if($subhlevel > $hlevel) {
288 $rv.=$subheadline.$secs[$count*2];
289 }
290 if($subhlevel <= $hlevel) {
291 $break=true;
292 }
293 $count++;
294
295 }
296 }
297 # reinsert stripped tags
298 $rv=$parser->unstrip($rv,$striparray);
299 $rv=$parser->unstripNoWiki($rv,$striparray);
300 $rv=trim($rv);
301 return $rv;
302
303 }
304
305 /**
306 * @return int The oldid of the article that is to be shown, 0 for the
307 * current revision
308 */
309 function getOldID() {
310 if ( is_null( $this->mOldId ) ) {
311 $this->mOldId = $this->getOldIDFromRequest();
312 }
313 return $this->mOldId;
314 }
315
316 /**
317 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
318 *
319 * @return int The old id for the request
320 */
321 function getOldIDFromRequest() {
322 global $wgRequest;
323 $this->mRedirectUrl = false;
324 $oldid = $wgRequest->getVal( 'oldid' );
325 if ( isset( $oldid ) ) {
326 $oldid = intval( $oldid );
327 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
328 $nextid = $this->mTitle->getNextRevisionID( $oldid );
329 if ( $nextid ) {
330 $oldid = $nextid;
331 } else {
332 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
333 }
334 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
335 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
336 if ( $previd ) {
337 $oldid = $previd;
338 } else {
339 # TODO
340 }
341 }
342 $lastid = $oldid;
343 }
344 if ( !$oldid ) {
345 $oldid = 0;
346 }
347 return $oldid;
348 }
349
350 /**
351 * Load the revision (including text) into this object
352 */
353 function loadContent() {
354 if ( $this->mContentLoaded ) return;
355
356 # Query variables :P
357 $oldid = $this->getOldID();
358
359 $fname = 'Article::loadContent';
360
361 # Pre-fill content with error message so that if something
362 # fails we'll have something telling us what we intended.
363
364 $t = $this->mTitle->getPrefixedText();
365
366 $this->mOldId = $oldid;
367 $this->fetchContent( $oldid );
368 }
369
370
371 /**
372 * Fetch a page record with the given conditions
373 * @param Database $dbr
374 * @param array $conditions
375 * @access private
376 */
377 function pageData( &$dbr, $conditions ) {
378 $fields = array(
379 'page_id',
380 'page_namespace',
381 'page_title',
382 'page_restrictions',
383 'page_counter',
384 'page_is_redirect',
385 'page_is_new',
386 'page_random',
387 'page_touched',
388 'page_latest',
389 'page_len' ) ;
390 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
391 $row = $dbr->selectRow( 'page',
392 $fields,
393 $conditions,
394 'Article::pageData' );
395 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
396 return $row ;
397 }
398
399 /**
400 * @param Database $dbr
401 * @param Title $title
402 */
403 function pageDataFromTitle( &$dbr, $title ) {
404 return $this->pageData( $dbr, array(
405 'page_namespace' => $title->getNamespace(),
406 'page_title' => $title->getDBkey() ) );
407 }
408
409 /**
410 * @param Database $dbr
411 * @param int $id
412 */
413 function pageDataFromId( &$dbr, $id ) {
414 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 }
416
417 /**
418 * Set the general counter, title etc data loaded from
419 * some source.
420 *
421 * @param object $data
422 * @access private
423 */
424 function loadPageData( $data ) {
425 $this->mTitle->mArticleID = $data->page_id;
426 $this->mTitle->loadRestrictions( $data->page_restrictions );
427 $this->mTitle->mRestrictionsLoaded = true;
428
429 $this->mCounter = $data->page_counter;
430 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
431 $this->mIsRedirect = $data->page_is_redirect;
432 $this->mLatest = $data->page_latest;
433
434 $this->mDataLoaded = true;
435 }
436
437 /**
438 * Get text of an article from database
439 * Does *NOT* follow redirects.
440 * @param int $oldid 0 for whatever the latest revision is
441 * @return string
442 */
443 function fetchContent( $oldid = 0 ) {
444 if ( $this->mContentLoaded ) {
445 return $this->mContent;
446 }
447
448 $dbr =& $this->getDB();
449 $fname = 'Article::fetchContent';
450
451 # Pre-fill content with error message so that if something
452 # fails we'll have something telling us what we intended.
453 $t = $this->mTitle->getPrefixedText();
454 if( $oldid ) {
455 $t .= ',oldid='.$oldid;
456 }
457 $this->mContent = wfMsg( 'missingarticle', $t ) ;
458
459 if( $oldid ) {
460 $revision = Revision::newFromId( $oldid );
461 if( is_null( $revision ) ) {
462 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
463 return false;
464 }
465 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
466 if( !$data ) {
467 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
468 return false;
469 }
470 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
471 $this->loadPageData( $data );
472 } else {
473 if( !$this->mDataLoaded ) {
474 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
475 if( !$data ) {
476 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
477 return false;
478 }
479 $this->loadPageData( $data );
480 }
481 $revision = Revision::newFromId( $this->mLatest );
482 if( is_null( $revision ) ) {
483 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
484 return false;
485 }
486 }
487
488 $this->mContent = $revision->getText();
489
490 $this->mUser = $revision->getUser();
491 $this->mUserText = $revision->getUserText();
492 $this->mComment = $revision->getComment();
493 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
494
495 $this->mRevIdFetched = $revision->getID();
496 $this->mContentLoaded = true;
497 $this->mRevision =& $revision;
498
499 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
500
501 return $this->mContent;
502 }
503
504 /**
505 * Read/write accessor to select FOR UPDATE
506 *
507 * @param mixed $x
508 */
509 function forUpdate( $x = NULL ) {
510 return wfSetVar( $this->mForUpdate, $x );
511 }
512
513 /**
514 * Get the database which should be used for reads
515 *
516 * @return Database
517 */
518 function &getDB() {
519 $ret =& wfGetDB( DB_MASTER );
520 return $ret;
521 }
522
523 /**
524 * Get options for all SELECT statements
525 *
526 * @param array $options an optional options array which'll be appended to
527 * the default
528 * @return array Options
529 */
530 function getSelectOptions( $options = '' ) {
531 if ( $this->mForUpdate ) {
532 if ( is_array( $options ) ) {
533 $options[] = 'FOR UPDATE';
534 } else {
535 $options = 'FOR UPDATE';
536 }
537 }
538 return $options;
539 }
540
541 /**
542 * @return int Page ID
543 */
544 function getID() {
545 if( $this->mTitle ) {
546 return $this->mTitle->getArticleID();
547 } else {
548 return 0;
549 }
550 }
551
552 /**
553 * @return bool Whether or not the page exists in the database
554 */
555 function exists() {
556 return $this->getId() != 0;
557 }
558
559 /**
560 * @return int The view count for the page
561 */
562 function getCount() {
563 if ( -1 == $this->mCounter ) {
564 $id = $this->getID();
565 $dbr =& wfGetDB( DB_SLAVE );
566 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
567 'Article::getCount', $this->getSelectOptions() );
568 }
569 return $this->mCounter;
570 }
571
572 /**
573 * Determine whether a page would be suitable for being counted as an
574 * article in the site_stats table based on the title & its content
575 *
576 * @param string $text Text to analyze
577 * @return bool
578 */
579 function isCountable( $text ) {
580 global $wgUseCommaCount;
581
582 $token = $wgUseCommaCount ? ',' : '[[';
583 return
584 $this->mTitle->getNamespace() == NS_MAIN
585 && ! $this->isRedirect( $text )
586 && in_string( $token, $text );
587 }
588
589 /**
590 * Tests if the article text represents a redirect
591 *
592 * @param string $text
593 * @return bool
594 */
595 function isRedirect( $text = false ) {
596 if ( $text === false ) {
597 $this->loadContent();
598 $titleObj = Title::newFromRedirect( $this->fetchContent() );
599 } else {
600 $titleObj = Title::newFromRedirect( $text );
601 }
602 return $titleObj !== NULL;
603 }
604
605 /**
606 * Returns true if the currently-referenced revision is the current edit
607 * to this page (and it exists).
608 * @return bool
609 */
610 function isCurrent() {
611 return $this->exists() &&
612 isset( $this->mRevision ) &&
613 $this->mRevision->isCurrent();
614 }
615
616 /**
617 * Loads everything except the text
618 * This isn't necessary for all uses, so it's only done if needed.
619 * @access private
620 */
621 function loadLastEdit() {
622 if ( -1 != $this->mUser )
623 return;
624
625 # New or non-existent articles have no user information
626 $id = $this->getID();
627 if ( 0 == $id ) return;
628
629 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
630 if( !is_null( $this->mLastRevision ) ) {
631 $this->mUser = $this->mLastRevision->getUser();
632 $this->mUserText = $this->mLastRevision->getUserText();
633 $this->mTimestamp = $this->mLastRevision->getTimestamp();
634 $this->mComment = $this->mLastRevision->getComment();
635 $this->mMinorEdit = $this->mLastRevision->isMinor();
636 $this->mRevIdFetched = $this->mLastRevision->getID();
637 }
638 }
639
640 function getTimestamp() {
641 $this->loadLastEdit();
642 return wfTimestamp(TS_MW, $this->mTimestamp);
643 }
644
645 function getUser() {
646 $this->loadLastEdit();
647 return $this->mUser;
648 }
649
650 function getUserText() {
651 $this->loadLastEdit();
652 return $this->mUserText;
653 }
654
655 function getComment() {
656 $this->loadLastEdit();
657 return $this->mComment;
658 }
659
660 function getMinorEdit() {
661 $this->loadLastEdit();
662 return $this->mMinorEdit;
663 }
664
665 function getRevIdFetched() {
666 $this->loadLastEdit();
667 return $this->mRevIdFetched;
668 }
669
670 function getContributors($limit = 0, $offset = 0) {
671 $fname = 'Article::getContributors';
672
673 # XXX: this is expensive; cache this info somewhere.
674
675 $title = $this->mTitle;
676 $contribs = array();
677 $dbr =& wfGetDB( DB_SLAVE );
678 $revTable = $dbr->tableName( 'revision' );
679 $userTable = $dbr->tableName( 'user' );
680 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
681 $ns = $title->getNamespace();
682 $user = $this->getUser();
683 $pageId = $this->getId();
684
685 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
686 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
687 WHERE rev_page = $pageId
688 AND rev_user != $user
689 GROUP BY rev_user, rev_user_text, user_real_name
690 ORDER BY timestamp DESC";
691
692 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
693 $sql .= ' '. $this->getSelectOptions();
694
695 $res = $dbr->query($sql, $fname);
696
697 while ( $line = $dbr->fetchObject( $res ) ) {
698 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
699 }
700
701 $dbr->freeResult($res);
702 return $contribs;
703 }
704
705 /**
706 * This is the default action of the script: just view the page of
707 * the given title.
708 */
709 function view() {
710 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgContLang;
711 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
712 global $wgUseTrackbacks;
713 $sk = $wgUser->getSkin();
714
715 $fname = 'Article::view';
716 wfProfileIn( $fname );
717 $parserCache =& ParserCache::singleton();
718 # Get variables from query string
719 $oldid = $this->getOldID();
720
721 # getOldID may want us to redirect somewhere else
722 if ( $this->mRedirectUrl ) {
723 $wgOut->redirect( $this->mRedirectUrl );
724 wfProfileOut( $fname );
725 return;
726 }
727
728 $diff = $wgRequest->getVal( 'diff' );
729 $rcid = $wgRequest->getVal( 'rcid' );
730 $rdfrom = $wgRequest->getVal( 'rdfrom' );
731
732 $wgOut->setArticleFlag( true );
733 $wgOut->setRobotpolicy( 'index,follow' );
734 # If we got diff and oldid in the query, we want to see a
735 # diff page instead of the article.
736
737 if ( !is_null( $diff ) ) {
738 require_once( 'DifferenceEngine.php' );
739 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
740
741 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
742 // DifferenceEngine directly fetched the revision:
743 $this->mRevIdFetched = $de->mNewid;
744 $de->showDiffPage();
745
746 if( $diff == 0 ) {
747 # Run view updates for current revision only
748 $this->viewUpdates();
749 }
750 wfProfileOut( $fname );
751 return;
752 }
753
754 if ( empty( $oldid ) && $this->checkTouched() ) {
755 $wgOut->setETag($parserCache->getETag($this, $wgUser));
756
757 if( $wgOut->checkLastModified( $this->mTouched ) ){
758 wfProfileOut( $fname );
759 return;
760 } else if ( $this->tryFileCache() ) {
761 # tell wgOut that output is taken care of
762 $wgOut->disable();
763 $this->viewUpdates();
764 wfProfileOut( $fname );
765 return;
766 }
767 }
768 # Should the parser cache be used?
769 $pcache = $wgEnableParserCache &&
770 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
771 $this->exists() &&
772 empty( $oldid );
773 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
774 if ( $wgUser->getOption( 'stubthreshold' ) ) {
775 wfIncrStats( 'pcache_miss_stub' );
776 }
777
778 $wasRedirected = false;
779 if ( isset( $this->mRedirectedFrom ) ) {
780 // This is an internally redirected page view.
781 // We'll need a backlink to the source page for navigation.
782 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
783 $sk = $wgUser->getSkin();
784 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
785 $s = wfMsg( 'redirectedfrom', $redir );
786 $wgOut->setSubtitle( $s );
787 $wasRedirected = true;
788 }
789 } elseif ( !empty( $rdfrom ) ) {
790 // This is an externally redirected view, from some other wiki.
791 // If it was reported from a trusted site, supply a backlink.
792 global $wgRedirectSources;
793 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
794 $sk = $wgUser->getSkin();
795 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
796 $s = wfMsg( 'redirectedfrom', $redir );
797 $wgOut->setSubtitle( $s );
798 $wasRedirected = true;
799 }
800 }
801
802 $outputDone = false;
803 if ( $pcache ) {
804 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
805 $outputDone = true;
806 }
807 }
808 if ( !$outputDone ) {
809 $text = $this->getContent();
810 if ( $text === false ) {
811 # Failed to load, replace text with error message
812 $t = $this->mTitle->getPrefixedText();
813 if( $oldid ) {
814 $t .= ',oldid='.$oldid;
815 $text = wfMsg( 'missingarticle', $t );
816 } else {
817 $text = wfMsg( 'noarticletext', $t );
818 }
819 }
820
821 # Another whitelist check in case oldid is altering the title
822 if ( !$this->mTitle->userCanRead() ) {
823 $wgOut->loginToUse();
824 $wgOut->output();
825 exit;
826 }
827
828 # We're looking at an old revision
829
830 if ( !empty( $oldid ) ) {
831 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
832 $wgOut->setRobotpolicy( 'noindex,follow' );
833 }
834 }
835 if( !$outputDone ) {
836 /**
837 * @fixme: this hook doesn't work most of the time, as it doesn't
838 * trigger when the parser cache is used.
839 */
840 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
841 $wgOut->setRevisionId( $this->getRevIdFetched() );
842 # wrap user css and user js in pre and don't parse
843 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
844 if (
845 $this->mTitle->getNamespace() == NS_USER &&
846 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
847 ) {
848 $wgOut->addWikiText( wfMsg('clearyourcache'));
849 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
850 } else if ( $rt = Title::newFromRedirect( $text ) ) {
851 # Display redirect
852 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
853 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
854 if( !$wasRedirected ) {
855 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
856 }
857 $targetUrl = $rt->escapeLocalURL();
858 $titleText = htmlspecialchars( $rt->getPrefixedText() );
859 $link = $sk->makeLinkObj( $rt );
860
861 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
862 '<span class="redirectText">'.$link.'</span>' );
863
864 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
865 $wgOut->addParserOutputNoText( $parseout );
866 } else if ( $pcache ) {
867 # Display content and save to parser cache
868 $wgOut->addPrimaryWikiText( $text, $this );
869 } else {
870 # Display content, don't attempt to save to parser cache
871
872 # Don't show section-edit links on old revisions... this way lies madness.
873 if( !$this->isCurrent() ) {
874 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
875 }
876 # Display content and don't save to parser cache
877 $wgOut->addPrimaryWikiText( $text, $this, false );
878
879 if( !$this->isCurrent() ) {
880 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
881 }
882 }
883 }
884 /* title may have been set from the cache */
885 $t = $wgOut->getPageTitle();
886 if( empty( $t ) ) {
887 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
888 }
889
890 # If we have been passed an &rcid= parameter, we want to give the user a
891 # chance to mark this new article as patrolled.
892 if ( $wgUseRCPatrol
893 && !is_null($rcid)
894 && $rcid != 0
895 && $wgUser->isLoggedIn()
896 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
897 {
898 $wgOut->addHTML(
899 "<div class='patrollink'>" .
900 wfMsg ( 'markaspatrolledlink',
901 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
902 ) .
903 '</div>'
904 );
905 }
906
907 # Trackbacks
908 if ($wgUseTrackbacks)
909 $this->addTrackbacks();
910
911 $this->viewUpdates();
912 wfProfileOut( $fname );
913 }
914
915 function addTrackbacks() {
916 global $wgOut, $wgUser;
917
918 $dbr =& wfGetDB(DB_SLAVE);
919 $tbs = $dbr->select(
920 /* FROM */ 'trackbacks',
921 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
922 /* WHERE */ array('tb_page' => $this->getID())
923 );
924
925 if (!$dbr->numrows($tbs))
926 return;
927
928 $tbtext = "";
929 while ($o = $dbr->fetchObject($tbs)) {
930 $rmvtxt = "";
931 if ($wgUser->isSysop()) {
932 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
933 . $o->tb_id . "&token=" . $wgUser->editToken());
934 $rmvtxt = wfMsg('trackbackremove', $delurl);
935 }
936 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
937 $o->tb_title,
938 $o->tb_url,
939 $o->tb_ex,
940 $o->tb_name,
941 $rmvtxt);
942 }
943 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
944 }
945
946 function deletetrackback() {
947 global $wgUser, $wgRequest, $wgOut, $wgTitle;
948
949 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
950 $wgOut->addWikitext(wfMsg('sessionfailure'));
951 return;
952 }
953
954 if ((!$wgUser->isAllowed('delete'))) {
955 $wgOut->sysopRequired();
956 return;
957 }
958
959 if (wfReadOnly()) {
960 $wgOut->readOnlyPage();
961 return;
962 }
963
964 $db =& wfGetDB(DB_MASTER);
965 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
966 $wgTitle->invalidateCache();
967 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
968 }
969
970 function render() {
971 global $wgOut;
972
973 $wgOut->setArticleBodyOnly(true);
974 $this->view();
975 }
976
977 /**
978 * Handle action=purge
979 */
980 function purge() {
981 global $wgUser, $wgRequest, $wgOut;
982
983 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
984 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
985 $this->doPurge();
986 }
987 } else {
988 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
989 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
990 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
991 $msg = str_replace( '$1',
992 "<form method=\"post\" action=\"$action\">\n" .
993 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
994 "</form>\n", $msg );
995
996 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
997 $wgOut->setRobotpolicy( 'noindex,nofollow' );
998 $wgOut->addHTML( $msg );
999 }
1000 }
1001
1002 /**
1003 * Perform the actions of a page purging
1004 */
1005 function doPurge() {
1006 global $wgUseSquid;
1007 // Invalidate the cache
1008 $this->mTitle->invalidateCache();
1009
1010 if ( $wgUseSquid ) {
1011 // Commit the transaction before the purge is sent
1012 $dbw = wfGetDB( DB_MASTER );
1013 $dbw->immediateCommit();
1014
1015 // Send purge
1016 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1017 $update->doUpdate();
1018 }
1019 $this->view();
1020 }
1021
1022 /**
1023 * Insert a new empty page record for this article.
1024 * This *must* be followed up by creating a revision
1025 * and running $this->updateToLatest( $rev_id );
1026 * or else the record will be left in a funky state.
1027 * Best if all done inside a transaction.
1028 *
1029 * @param Database $dbw
1030 * @param string $restrictions
1031 * @return int The newly created page_id key
1032 * @access private
1033 */
1034 function insertOn( &$dbw, $restrictions = '' ) {
1035 $fname = 'Article::insertOn';
1036 wfProfileIn( $fname );
1037
1038 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1039 $dbw->insert( 'page', array(
1040 'page_id' => $page_id,
1041 'page_namespace' => $this->mTitle->getNamespace(),
1042 'page_title' => $this->mTitle->getDBkey(),
1043 'page_counter' => 0,
1044 'page_restrictions' => $restrictions,
1045 'page_is_redirect' => 0, # Will set this shortly...
1046 'page_is_new' => 1,
1047 'page_random' => wfRandom(),
1048 'page_touched' => $dbw->timestamp(),
1049 'page_latest' => 0, # Fill this in shortly...
1050 'page_len' => 0, # Fill this in shortly...
1051 ), $fname );
1052 $newid = $dbw->insertId();
1053
1054 $this->mTitle->resetArticleId( $newid );
1055
1056 wfProfileOut( $fname );
1057 return $newid;
1058 }
1059
1060 /**
1061 * Update the page record to point to a newly saved revision.
1062 *
1063 * @param Database $dbw
1064 * @param Revision $revision For ID number, and text used to set
1065 length and redirect status fields
1066 * @param int $lastRevision If given, will not overwrite the page field
1067 * when different from the currently set value.
1068 * Giving 0 indicates the new page flag should
1069 * be set on.
1070 * @return bool true on success, false on failure
1071 * @access private
1072 */
1073 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1074 $fname = 'Article::updateToRevision';
1075 wfProfileIn( $fname );
1076
1077 $conditions = array( 'page_id' => $this->getId() );
1078 if( !is_null( $lastRevision ) ) {
1079 # An extra check against threads stepping on each other
1080 $conditions['page_latest'] = $lastRevision;
1081 }
1082
1083 $text = $revision->getText();
1084 $dbw->update( 'page',
1085 array( /* SET */
1086 'page_latest' => $revision->getId(),
1087 'page_touched' => $dbw->timestamp(),
1088 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1089 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1090 'page_len' => strlen( $text ),
1091 ),
1092 $conditions,
1093 $fname );
1094
1095 wfProfileOut( $fname );
1096 return ( $dbw->affectedRows() != 0 );
1097 }
1098
1099 /**
1100 * If the given revision is newer than the currently set page_latest,
1101 * update the page record. Otherwise, do nothing.
1102 *
1103 * @param Database $dbw
1104 * @param Revision $revision
1105 */
1106 function updateIfNewerOn( &$dbw, $revision ) {
1107 $fname = 'Article::updateIfNewerOn';
1108 wfProfileIn( $fname );
1109
1110 $row = $dbw->selectRow(
1111 array( 'revision', 'page' ),
1112 array( 'rev_id', 'rev_timestamp' ),
1113 array(
1114 'page_id' => $this->getId(),
1115 'page_latest=rev_id' ),
1116 $fname );
1117 if( $row ) {
1118 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1119 wfProfileOut( $fname );
1120 return false;
1121 }
1122 $prev = $row->rev_id;
1123 } else {
1124 # No or missing previous revision; mark the page as new
1125 $prev = 0;
1126 }
1127
1128 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1129 wfProfileOut( $fname );
1130 return $ret;
1131 }
1132
1133 /**
1134 * Insert a new article into the database
1135 * @access private
1136 */
1137 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1138 global $wgUser;
1139
1140 $fname = 'Article::insertNewArticle';
1141 wfProfileIn( $fname );
1142
1143 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1144 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1145 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1146 wfProfileOut( $fname );
1147 return false;
1148 }
1149
1150 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1151 $this->mTotalAdjustment = 1;
1152
1153 $ns = $this->mTitle->getNamespace();
1154 $ttl = $this->mTitle->getDBkey();
1155
1156 # If this is a comment, add the summary as headline
1157 if($comment && $summary!="") {
1158 $text="== {$summary} ==\n\n".$text;
1159 }
1160 $text = $this->preSaveTransform( $text );
1161
1162 /* Silently ignore minoredit if not allowed */
1163 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1164 $now = wfTimestampNow();
1165
1166 $dbw =& wfGetDB( DB_MASTER );
1167
1168 # Add the page record; stake our claim on this title!
1169 $newid = $this->insertOn( $dbw );
1170
1171 # Save the revision text...
1172 $revision = new Revision( array(
1173 'page' => $newid,
1174 'comment' => $summary,
1175 'minor_edit' => $isminor,
1176 'text' => $text
1177 ) );
1178 $revisionId = $revision->insertOn( $dbw );
1179
1180 $this->mTitle->resetArticleID( $newid );
1181
1182 # Update the page record with revision data
1183 $this->updateRevisionOn( $dbw, $revision, 0 );
1184
1185 Article::onArticleCreate( $this->mTitle );
1186 if(!$suppressRC) {
1187 require_once( 'RecentChange.php' );
1188 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1189 '', strlen( $text ), $revisionId );
1190 }
1191
1192 if ($watchthis) {
1193 if(!$this->mTitle->userIsWatching()) $this->watch();
1194 } else {
1195 if ( $this->mTitle->userIsWatching() ) {
1196 $this->unwatch();
1197 }
1198 }
1199
1200 # The talk page isn't in the regular link tables, so we need to update manually:
1201 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1202 $dbw->update( 'page',
1203 array( 'page_touched' => $dbw->timestamp($now) ),
1204 array( 'page_namespace' => $talkns,
1205 'page_title' => $ttl ),
1206 $fname );
1207
1208 # standard deferred updates
1209 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1210
1211 $oldid = 0; # new article
1212 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1213
1214 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1215 $summary, $isminor,
1216 $watchthis, NULL ) );
1217 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1218 $summary, $isminor,
1219 $watchthis, NULL ) );
1220 wfProfileOut( $fname );
1221 }
1222
1223 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1224 $this->replaceSection( $section, $text, $summary, $edittime );
1225 }
1226
1227 /**
1228 * @return string Complete article text, or null if error
1229 */
1230 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1231 $fname = 'Article::replaceSection';
1232 wfProfileIn( $fname );
1233
1234 if ($section != '') {
1235 if( is_null( $edittime ) ) {
1236 $rev = Revision::newFromTitle( $this->mTitle );
1237 } else {
1238 $dbw =& wfGetDB( DB_MASTER );
1239 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1240 }
1241 if( is_null( $rev ) ) {
1242 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1243 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1244 return null;
1245 }
1246 $oldtext = $rev->getText();
1247
1248 if($section=='new') {
1249 if($summary) $subject="== {$summary} ==\n\n";
1250 $text=$oldtext."\n\n".$subject.$text;
1251 } else {
1252
1253 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1254 # comments to be stripped as well)
1255 $striparray=array();
1256 $parser=new Parser();
1257 $parser->mOutputType=OT_WIKI;
1258 $parser->mOptions = new ParserOptions();
1259 $oldtext=$parser->strip($oldtext, $striparray, true);
1260
1261 # now that we can be sure that no pseudo-sections are in the source,
1262 # split it up
1263 # Unfortunately we can't simply do a preg_replace because that might
1264 # replace the wrong section, so we have to use the section counter instead
1265 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1266 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1267 $secs[$section*2]=$text."\n\n"; // replace with edited
1268
1269 # section 0 is top (intro) section
1270 if($section!=0) {
1271
1272 # headline of old section - we need to go through this section
1273 # to determine if there are any subsections that now need to
1274 # be erased, as the mother section has been replaced with
1275 # the text of all subsections.
1276 $headline=$secs[$section*2-1];
1277 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1278 $hlevel=$matches[1];
1279
1280 # determine headline level for wikimarkup headings
1281 if(strpos($hlevel,'=')!==false) {
1282 $hlevel=strlen($hlevel);
1283 }
1284
1285 $secs[$section*2-1]=''; // erase old headline
1286 $count=$section+1;
1287 $break=false;
1288 while(!empty($secs[$count*2-1]) && !$break) {
1289
1290 $subheadline=$secs[$count*2-1];
1291 preg_match(
1292 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1293 $subhlevel=$matches[1];
1294 if(strpos($subhlevel,'=')!==false) {
1295 $subhlevel=strlen($subhlevel);
1296 }
1297 if($subhlevel > $hlevel) {
1298 // erase old subsections
1299 $secs[$count*2-1]='';
1300 $secs[$count*2]='';
1301 }
1302 if($subhlevel <= $hlevel) {
1303 $break=true;
1304 }
1305 $count++;
1306
1307 }
1308
1309 }
1310 $text=join('',$secs);
1311 # reinsert the stuff that we stripped out earlier
1312 $text=$parser->unstrip($text,$striparray);
1313 $text=$parser->unstripNoWiki($text,$striparray);
1314 }
1315
1316 }
1317 wfProfileOut( $fname );
1318 return $text;
1319 }
1320
1321 /**
1322 * Change an existing article. Puts the previous version back into the old table, updates RC
1323 * and all necessary caches, mostly via the deferred update array.
1324 *
1325 * It is possible to call this function from a command-line script, but note that you should
1326 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1327 */
1328 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1329 global $wgUser, $wgDBtransactions, $wgUseSquid;
1330 global $wgPostCommitUpdateList, $wgUseFileCache;
1331
1332 $fname = 'Article::updateArticle';
1333 wfProfileIn( $fname );
1334 $good = true;
1335
1336 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1337 &$summary, &$minor,
1338 &$watchthis, &$sectionanchor ) ) ) {
1339 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1340 wfProfileOut( $fname );
1341 return false;
1342 }
1343
1344 $isminor = $minor && $wgUser->isAllowed('minoredit');
1345 $redir = (int)$this->isRedirect( $text );
1346
1347 $text = $this->preSaveTransform( $text );
1348 $dbw =& wfGetDB( DB_MASTER );
1349 $now = wfTimestampNow();
1350
1351 # Update article, but only if changed.
1352
1353 # It's important that we either rollback or complete, otherwise an attacker could
1354 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1355 # could conceivably have the same effect, especially if cur is locked for long periods.
1356 if( !$wgDBtransactions ) {
1357 $userAbort = ignore_user_abort( true );
1358 }
1359
1360 $oldtext = $this->getContent();
1361 $oldsize = strlen( $oldtext );
1362 $newsize = strlen( $text );
1363 $lastRevision = 0;
1364 $revisionId = 0;
1365
1366 if ( 0 != strcmp( $text, $oldtext ) ) {
1367 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1368 - (int)$this->isCountable( $oldtext );
1369 $this->mTotalAdjustment = 0;
1370 $now = wfTimestampNow();
1371
1372 $lastRevision = $dbw->selectField(
1373 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1374
1375 $revision = new Revision( array(
1376 'page' => $this->getId(),
1377 'comment' => $summary,
1378 'minor_edit' => $isminor,
1379 'text' => $text
1380 ) );
1381
1382 $dbw->immediateCommit();
1383 $dbw->begin();
1384 $revisionId = $revision->insertOn( $dbw );
1385
1386 # Update page
1387 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1388
1389 if( !$ok ) {
1390 /* Belated edit conflict! Run away!! */
1391 $good = false;
1392 $dbw->rollback();
1393 } else {
1394 # Update recentchanges and purge cache and whatnot
1395 require_once( 'RecentChange.php' );
1396 $bot = (int)($wgUser->isBot() || $forceBot);
1397 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1398 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1399 $revisionId );
1400 $dbw->commit();
1401
1402 // Update caches outside the main transaction
1403 Article::onArticleEdit( $this->mTitle );
1404 }
1405 } else {
1406 // Keep the same revision ID, but do some updates on it
1407 $revisionId = $this->getRevIdFetched();
1408 }
1409
1410 if( !$wgDBtransactions ) {
1411 ignore_user_abort( $userAbort );
1412 }
1413
1414 if ( $good ) {
1415 if ($watchthis) {
1416 if (!$this->mTitle->userIsWatching()) {
1417 $dbw->immediateCommit();
1418 $dbw->begin();
1419 $this->watch();
1420 $dbw->commit();
1421 }
1422 } else {
1423 if ( $this->mTitle->userIsWatching() ) {
1424 $dbw->immediateCommit();
1425 $dbw->begin();
1426 $this->unwatch();
1427 $dbw->commit();
1428 }
1429 }
1430 # standard deferred updates
1431 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1432
1433
1434 $urls = array();
1435 # Invalidate caches of all articles using this article as a template
1436
1437 # Template namespace
1438 # Purge all articles linking here
1439 $titles = $this->mTitle->getTemplateLinksTo();
1440 Title::touchArray( $titles );
1441 if ( $wgUseSquid ) {
1442 foreach ( $titles as $title ) {
1443 $urls[] = $title->getInternalURL();
1444 }
1445 }
1446
1447 # Squid updates
1448 if ( $wgUseSquid ) {
1449 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1450 $u = new SquidUpdate( $urls );
1451 array_push( $wgPostCommitUpdateList, $u );
1452 }
1453
1454 # File cache
1455 if ( $wgUseFileCache ) {
1456 $cm = new CacheManager($this->mTitle);
1457 @unlink($cm->fileCacheName());
1458 }
1459
1460 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1461 }
1462 wfRunHooks( 'ArticleSaveComplete',
1463 array( &$this, &$wgUser, $text,
1464 $summary, $minor,
1465 $watchthis, $sectionanchor ) );
1466 wfProfileOut( $fname );
1467 return $good;
1468 }
1469
1470 /**
1471 * After we've either updated or inserted the article, update
1472 * the link tables and redirect to the new page.
1473 */
1474 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1475 global $wgOut;
1476
1477 $fname = 'Article::showArticle';
1478 wfProfileIn( $fname );
1479
1480 # Output the redirect
1481 if( $this->isRedirect( $text ) )
1482 $r = 'redirect=no';
1483 else
1484 $r = '';
1485 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1486
1487 wfProfileOut( $fname );
1488 }
1489
1490 /**
1491 * Mark this particular edit as patrolled
1492 */
1493 function markpatrolled() {
1494 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1495 $wgOut->setRobotpolicy( 'noindex,follow' );
1496
1497 # Check RC patrol config. option
1498 if( !$wgUseRCPatrol ) {
1499 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1500 return;
1501 }
1502
1503 # Check permissions
1504 if( $wgUser->isLoggedIn() ) {
1505 if( !$wgUser->isAllowed( 'patrol' ) ) {
1506 $wgOut->permissionRequired( 'patrol' );
1507 return;
1508 }
1509 } else {
1510 $wgOut->loginToUse();
1511 return;
1512 }
1513
1514 $rcid = $wgRequest->getVal( 'rcid' );
1515 if ( !is_null ( $rcid ) )
1516 {
1517 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) ) ) {
1518 require_once( 'RecentChange.php' );
1519 RecentChange::markPatrolled( $rcid );
1520 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) );
1521 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1522 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1523 }
1524 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1525 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1526 }
1527 else
1528 {
1529 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1530 }
1531 }
1532
1533 /**
1534 * Add this page to $wgUser's watchlist
1535 */
1536
1537 function watch() {
1538
1539 global $wgUser, $wgOut;
1540
1541 if ( $wgUser->isAnon() ) {
1542 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1543 return;
1544 }
1545 if ( wfReadOnly() ) {
1546 $wgOut->readOnlyPage();
1547 return;
1548 }
1549
1550 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1551
1552 $wgUser->addWatch( $this->mTitle );
1553 $wgUser->saveSettings();
1554
1555 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1556
1557 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1558 $wgOut->setRobotpolicy( 'noindex,follow' );
1559
1560 $link = $this->mTitle->getPrefixedText();
1561 $text = wfMsg( 'addedwatchtext', $link );
1562 $wgOut->addWikiText( $text );
1563 }
1564
1565 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1566 }
1567
1568 /**
1569 * Stop watching a page
1570 */
1571
1572 function unwatch() {
1573
1574 global $wgUser, $wgOut;
1575
1576 if ( $wgUser->isAnon() ) {
1577 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1578 return;
1579 }
1580 if ( wfReadOnly() ) {
1581 $wgOut->readOnlyPage();
1582 return;
1583 }
1584
1585 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1586
1587 $wgUser->removeWatch( $this->mTitle );
1588 $wgUser->saveSettings();
1589
1590 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1591
1592 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1593 $wgOut->setRobotpolicy( 'noindex,follow' );
1594
1595 $link = $this->mTitle->getPrefixedText();
1596 $text = wfMsg( 'removedwatchtext', $link );
1597 $wgOut->addWikiText( $text );
1598 }
1599
1600 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1601 }
1602
1603 /**
1604 * action=protect handler
1605 */
1606 function protect() {
1607 require_once 'ProtectionForm.php';
1608 $form = new ProtectionForm( $this );
1609 $form->show();
1610 }
1611
1612 /**
1613 * action=unprotect handler (alias)
1614 */
1615 function unprotect() {
1616 $this->protect();
1617 }
1618
1619 /**
1620 * Update the article's restriction field, and leave a log entry.
1621 *
1622 * @param array $limit set of restriction keys
1623 * @param string $reason
1624 * @return bool true on success
1625 */
1626 function updateRestrictions( $limit = array(), $reason = '' ) {
1627 global $wgUser;
1628
1629 if ( !$wgUser->isAllowed( 'protect' ) ) {
1630 return false;
1631 }
1632
1633 if( wfReadOnly() ) {
1634 return false;
1635 }
1636
1637 $id = $this->mTitle->getArticleID();
1638 if ( 0 == $id ) {
1639 return false;
1640 }
1641
1642 $flat = Article::flattenRestrictions( $limit );
1643 $protecting = ($flat != '');
1644
1645 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1646 $limit, $reason ) ) ) {
1647
1648 $dbw =& wfGetDB( DB_MASTER );
1649 $dbw->update( 'page',
1650 array( /* SET */
1651 'page_touched' => $dbw->timestamp(),
1652 'page_restrictions' => $flat
1653 ), array( /* WHERE */
1654 'page_id' => $id
1655 ), 'Article::protect'
1656 );
1657
1658 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1659 $limit, $reason ) );
1660
1661 $log = new LogPage( 'protect' );
1662 if( $protecting ) {
1663 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$flat]" ) );
1664 } else {
1665 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1666 }
1667 }
1668 return true;
1669 }
1670
1671 /**
1672 * Take an array of page restrictions and flatten it to a string
1673 * suitable for insertion into the page_restrictions field.
1674 * @param array $limit
1675 * @return string
1676 * @access private
1677 */
1678 function flattenRestrictions( $limit ) {
1679 if( !is_array( $limit ) ) {
1680 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1681 }
1682 $bits = array();
1683 foreach( $limit as $action => $restrictions ) {
1684 if( $restrictions != '' ) {
1685 $bits[] = "$action=$restrictions";
1686 }
1687 }
1688 return implode( ':', $bits );
1689 }
1690
1691 /*
1692 * UI entry point for page deletion
1693 */
1694 function delete() {
1695 global $wgUser, $wgOut, $wgRequest;
1696 $fname = 'Article::delete';
1697 $confirm = $wgRequest->wasPosted() &&
1698 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1699 $reason = $wgRequest->getText( 'wpReason' );
1700
1701 # This code desperately needs to be totally rewritten
1702
1703 # Check permissions
1704 if( $wgUser->isAllowed( 'delete' ) ) {
1705 if( $wgUser->isBlocked() ) {
1706 $wgOut->blockedPage();
1707 return;
1708 }
1709 } else {
1710 $wgOut->permissionRequired( 'delete' );
1711 return;
1712 }
1713
1714 if( wfReadOnly() ) {
1715 $wgOut->readOnlyPage();
1716 return;
1717 }
1718
1719 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1720
1721 # Better double-check that it hasn't been deleted yet!
1722 $dbw =& wfGetDB( DB_MASTER );
1723 $conds = $this->mTitle->pageCond();
1724 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1725 if ( $latest === false ) {
1726 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1727 return;
1728 }
1729
1730 if( $confirm ) {
1731 $this->doDelete( $reason );
1732 return;
1733 }
1734
1735 # determine whether this page has earlier revisions
1736 # and insert a warning if it does
1737 $maxRevisions = 20;
1738 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1739
1740 if( count( $authors ) > 1 && !$confirm ) {
1741 $skin=$wgUser->getSkin();
1742 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1743 $wgOut->addHTML( $skin->historyLink() .'</b>');
1744 }
1745
1746 # If a single user is responsible for all revisions, find out who they are
1747 if ( count( $authors ) == $maxRevisions ) {
1748 // Query bailed out, too many revisions to find out if they're all the same
1749 $authorOfAll = false;
1750 } else {
1751 $authorOfAll = reset( $authors );
1752 foreach ( $authors as $author ) {
1753 if ( $authorOfAll != $author ) {
1754 $authorOfAll = false;
1755 break;
1756 }
1757 }
1758 }
1759 # Fetch article text
1760 $rev = Revision::newFromTitle( $this->mTitle );
1761
1762 if( !is_null( $rev ) ) {
1763 # if this is a mini-text, we can paste part of it into the deletion reason
1764 $text = $rev->getText();
1765
1766 #if this is empty, an earlier revision may contain "useful" text
1767 $blanked = false;
1768 if( $text == '' ) {
1769 $prev = $rev->getPrevious();
1770 if( $prev ) {
1771 $text = $prev->getText();
1772 $blanked = true;
1773 }
1774 }
1775
1776 $length = strlen( $text );
1777
1778 # this should not happen, since it is not possible to store an empty, new
1779 # page. Let's insert a standard text in case it does, though
1780 if( $length == 0 && $reason === '' ) {
1781 $reason = wfMsgForContent( 'exblank' );
1782 }
1783
1784 if( $length < 500 && $reason === '' ) {
1785 # comment field=255, let's grep the first 150 to have some user
1786 # space left
1787 global $wgContLang;
1788 $text = $wgContLang->truncate( $text, 150, '...' );
1789
1790 # let's strip out newlines
1791 $text = preg_replace( "/[\n\r]/", '', $text );
1792
1793 if( !$blanked ) {
1794 if( $authorOfAll === false ) {
1795 $reason = wfMsgForContent( 'excontent', $text );
1796 } else {
1797 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1798 }
1799 } else {
1800 $reason = wfMsgForContent( 'exbeforeblank', $text );
1801 }
1802 }
1803 }
1804
1805 return $this->confirmDelete( '', $reason );
1806 }
1807
1808 /**
1809 * Get the last N authors
1810 * @param int $num Number of revisions to get
1811 * @param string $revLatest The latest rev_id, selected from the master (optional)
1812 * @return array Array of authors, duplicates not removed
1813 */
1814 function getLastNAuthors( $num, $revLatest = 0 ) {
1815 $fname = 'Article::getLastNAuthors';
1816 wfProfileIn( $fname );
1817
1818 // First try the slave
1819 // If that doesn't have the latest revision, try the master
1820 $continue = 2;
1821 $db =& wfGetDB( DB_SLAVE );
1822 do {
1823 $res = $db->select( array( 'page', 'revision' ),
1824 array( 'rev_id', 'rev_user_text' ),
1825 array(
1826 'page_namespace' => $this->mTitle->getNamespace(),
1827 'page_title' => $this->mTitle->getDBkey(),
1828 'rev_page = page_id'
1829 ), $fname, $this->getSelectOptions( array(
1830 'ORDER BY' => 'rev_timestamp DESC',
1831 'LIMIT' => $num
1832 ) )
1833 );
1834 if ( !$res ) {
1835 wfProfileOut( $fname );
1836 return array();
1837 }
1838 $row = $db->fetchObject( $res );
1839 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1840 $db =& wfGetDB( DB_MASTER );
1841 $continue--;
1842 } else {
1843 $continue = 0;
1844 }
1845 } while ( $continue );
1846
1847 $authors = array( $row->rev_user_text );
1848 while ( $row = $db->fetchObject( $res ) ) {
1849 $authors[] = $row->rev_user_text;
1850 }
1851 wfProfileOut( $fname );
1852 return $authors;
1853 }
1854
1855 /**
1856 * Output deletion confirmation dialog
1857 */
1858 function confirmDelete( $par, $reason ) {
1859 global $wgOut, $wgUser;
1860
1861 wfDebug( "Article::confirmDelete\n" );
1862
1863 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1864 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1865 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1866 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1867
1868 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1869
1870 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1871 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1872 $token = htmlspecialchars( $wgUser->editToken() );
1873
1874 $wgOut->addHTML( "
1875 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1876 <table border='0'>
1877 <tr>
1878 <td align='right'>
1879 <label for='wpReason'>{$delcom}:</label>
1880 </td>
1881 <td align='left'>
1882 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1883 </td>
1884 </tr>
1885 <tr>
1886 <td>&nbsp;</td>
1887 <td>
1888 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1889 </td>
1890 </tr>
1891 </table>
1892 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1893 </form>\n" );
1894
1895 $wgOut->returnToMain( false );
1896 }
1897
1898
1899 /**
1900 * Perform a deletion and output success or failure messages
1901 */
1902 function doDelete( $reason ) {
1903 global $wgOut, $wgUser;
1904 $fname = 'Article::doDelete';
1905 wfDebug( $fname."\n" );
1906
1907 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1908 if ( $this->doDeleteArticle( $reason ) ) {
1909 $deleted = $this->mTitle->getPrefixedText();
1910
1911 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1912 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1913
1914 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1915 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1916
1917 $wgOut->addWikiText( $text );
1918 $wgOut->returnToMain( false );
1919 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1920 } else {
1921 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1922 }
1923 }
1924 }
1925
1926 /**
1927 * Back-end article deletion
1928 * Deletes the article with database consistency, writes logs, purges caches
1929 * Returns success
1930 */
1931 function doDeleteArticle( $reason ) {
1932 global $wgUseSquid, $wgDeferredUpdateList;
1933 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1934
1935 $fname = 'Article::doDeleteArticle';
1936 wfDebug( $fname."\n" );
1937
1938 $dbw =& wfGetDB( DB_MASTER );
1939 $ns = $this->mTitle->getNamespace();
1940 $t = $this->mTitle->getDBkey();
1941 $id = $this->mTitle->getArticleID();
1942
1943 if ( $t == '' || $id == 0 ) {
1944 return false;
1945 }
1946
1947 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1948 array_push( $wgDeferredUpdateList, $u );
1949
1950 $linksTo = $this->mTitle->getLinksTo();
1951
1952 # Squid purging
1953 if ( $wgUseSquid ) {
1954 $urls = array(
1955 $this->mTitle->getInternalURL(),
1956 $this->mTitle->getInternalURL( 'history' )
1957 );
1958
1959 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1960 array_push( $wgPostCommitUpdateList, $u );
1961
1962 }
1963
1964 # Client and file cache invalidation
1965 Title::touchArray( $linksTo );
1966
1967
1968 // For now, shunt the revision data into the archive table.
1969 // Text is *not* removed from the text table; bulk storage
1970 // is left intact to avoid breaking block-compression or
1971 // immutable storage schemes.
1972 //
1973 // For backwards compatibility, note that some older archive
1974 // table entries will have ar_text and ar_flags fields still.
1975 //
1976 // In the future, we may keep revisions and mark them with
1977 // the rev_deleted field, which is reserved for this purpose.
1978 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1979 array(
1980 'ar_namespace' => 'page_namespace',
1981 'ar_title' => 'page_title',
1982 'ar_comment' => 'rev_comment',
1983 'ar_user' => 'rev_user',
1984 'ar_user_text' => 'rev_user_text',
1985 'ar_timestamp' => 'rev_timestamp',
1986 'ar_minor_edit' => 'rev_minor_edit',
1987 'ar_rev_id' => 'rev_id',
1988 'ar_text_id' => 'rev_text_id',
1989 ), array(
1990 'page_id' => $id,
1991 'page_id = rev_page'
1992 ), $fname
1993 );
1994
1995 # Now that it's safely backed up, delete it
1996 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1997 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1998
1999 if ($wgUseTrackbacks)
2000 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2001
2002 # Clean up recentchanges entries...
2003 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2004
2005 # Finally, clean up the link tables
2006 $t = $this->mTitle->getPrefixedDBkey();
2007
2008 Article::onArticleDelete( $this->mTitle );
2009
2010 # Delete outgoing links
2011 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2012 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2013 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2014 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2015 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2016
2017 # Log the deletion
2018 $log = new LogPage( 'delete' );
2019 $log->addEntry( 'delete', $this->mTitle, $reason );
2020
2021 # Clear the cached article id so the interface doesn't act like we exist
2022 $this->mTitle->resetArticleID( 0 );
2023 $this->mTitle->mArticleID = 0;
2024 return true;
2025 }
2026
2027 /**
2028 * Revert a modification
2029 */
2030 function rollback() {
2031 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2032 $fname = 'Article::rollback';
2033
2034 if( $wgUser->isAllowed( 'rollback' ) ) {
2035 if( $wgUser->isBlocked() ) {
2036 $wgOut->blockedPage();
2037 return;
2038 }
2039 } else {
2040 $wgOut->permissionRequired( 'rollback' );
2041 return;
2042 }
2043
2044 if ( wfReadOnly() ) {
2045 $wgOut->readOnlyPage( $this->getContent() );
2046 return;
2047 }
2048 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2049 array( $this->mTitle->getPrefixedText(),
2050 $wgRequest->getVal( 'from' ) ) ) ) {
2051 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2052 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2053 return;
2054 }
2055 $dbw =& wfGetDB( DB_MASTER );
2056
2057 # Enhanced rollback, marks edits rc_bot=1
2058 $bot = $wgRequest->getBool( 'bot' );
2059
2060 # Replace all this user's current edits with the next one down
2061 $tt = $this->mTitle->getDBKey();
2062 $n = $this->mTitle->getNamespace();
2063
2064 # Get the last editor, lock table exclusively
2065 $dbw->begin();
2066 $current = Revision::newFromTitle( $this->mTitle );
2067 if( is_null( $current ) ) {
2068 # Something wrong... no page?
2069 $dbw->rollback();
2070 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2071 return;
2072 }
2073
2074 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2075 if( $from != $current->getUserText() ) {
2076 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2077 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2078 htmlspecialchars( $this->mTitle->getPrefixedText()),
2079 htmlspecialchars( $from ),
2080 htmlspecialchars( $current->getUserText() ) ) );
2081 if( $current->getComment() != '') {
2082 $wgOut->addHTML(
2083 wfMsg( 'editcomment',
2084 htmlspecialchars( $current->getComment() ) ) );
2085 }
2086 return;
2087 }
2088
2089 # Get the last edit not by this guy
2090 $user = intval( $current->getUser() );
2091 $user_text = $dbw->addQuotes( $current->getUserText() );
2092 $s = $dbw->selectRow( 'revision',
2093 array( 'rev_id', 'rev_timestamp' ),
2094 array(
2095 'rev_page' => $current->getPage(),
2096 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2097 ), $fname,
2098 array(
2099 'USE INDEX' => 'page_timestamp',
2100 'ORDER BY' => 'rev_timestamp DESC' )
2101 );
2102 if( $s === false ) {
2103 # Something wrong
2104 $dbw->rollback();
2105 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2106 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2107 return;
2108 }
2109
2110 $set = array();
2111 if ( $bot ) {
2112 # Mark all reverted edits as bot
2113 $set['rc_bot'] = 1;
2114 }
2115 if ( $wgUseRCPatrol ) {
2116 # Mark all reverted edits as patrolled
2117 $set['rc_patrolled'] = 1;
2118 }
2119
2120 if ( $set ) {
2121 $dbw->update( 'recentchanges', $set,
2122 array( /* WHERE */
2123 'rc_cur_id' => $current->getPage(),
2124 'rc_user_text' => $current->getUserText(),
2125 "rc_timestamp > '{$s->rev_timestamp}'",
2126 ), $fname
2127 );
2128 }
2129
2130 # Get the edit summary
2131 $target = Revision::newFromId( $s->rev_id );
2132 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2133 $newComment = $wgRequest->getText( 'summary', $newComment );
2134
2135 # Save it!
2136 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2137 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2138 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2139
2140 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2141 Article::onArticleEdit( $this->mTitle );
2142
2143 $dbw->commit();
2144 $wgOut->returnToMain( false );
2145 }
2146
2147
2148 /**
2149 * Do standard deferred updates after page view
2150 * @access private
2151 */
2152 function viewUpdates() {
2153 global $wgDeferredUpdateList;
2154
2155 if ( 0 != $this->getID() ) {
2156 global $wgDisableCounters;
2157 if( !$wgDisableCounters ) {
2158 Article::incViewCount( $this->getID() );
2159 $u = new SiteStatsUpdate( 1, 0, 0 );
2160 array_push( $wgDeferredUpdateList, $u );
2161 }
2162 }
2163
2164 # Update newtalk / watchlist notification status
2165 global $wgUser;
2166 $wgUser->clearNotification( $this->mTitle );
2167 }
2168
2169 /**
2170 * Do standard deferred updates after page edit.
2171 * Every 1000th edit, prune the recent changes table.
2172 * @access private
2173 * @param string $text
2174 */
2175 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2176 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2177
2178 $fname = 'Article::editUpdates';
2179 wfProfileIn( $fname );
2180
2181 # Parse the text
2182 $options = new ParserOptions;
2183 $options->setTidy(true);
2184 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2185
2186 # Save it to the parser cache
2187 $parserCache =& ParserCache::singleton();
2188 $parserCache->save( $poutput, $this, $wgUser );
2189
2190 # Update the links tables
2191 $u = new LinksUpdate( $this->mTitle, $poutput );
2192 $u->doUpdate();
2193
2194 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2195 wfSeedRandom();
2196 if ( 0 == mt_rand( 0, 999 ) ) {
2197 # Periodically flush old entries from the recentchanges table.
2198 global $wgRCMaxAge;
2199
2200 $dbw =& wfGetDB( DB_MASTER );
2201 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2202 $recentchanges = $dbw->tableName( 'recentchanges' );
2203 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2204 $dbw->query( $sql );
2205 }
2206 }
2207
2208 $id = $this->getID();
2209 $title = $this->mTitle->getPrefixedDBkey();
2210 $shortTitle = $this->mTitle->getDBkey();
2211
2212 if ( 0 == $id ) {
2213 wfProfileOut( $fname );
2214 return;
2215 }
2216
2217 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2218 array_push( $wgDeferredUpdateList, $u );
2219 $u = new SearchUpdate( $id, $title, $text );
2220 array_push( $wgDeferredUpdateList, $u );
2221
2222 # If this is another user's talk page, update newtalk
2223
2224 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2225 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2226 $other = User::newFromName( $shortTitle );
2227 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2228 // An anonymous user
2229 $other = new User();
2230 $other->setName( $shortTitle );
2231 }
2232 if( $other ) {
2233 $other->setNewtalk( true );
2234 }
2235 }
2236 }
2237
2238 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2239 $wgMessageCache->replace( $shortTitle, $text );
2240 }
2241
2242 wfProfileOut( $fname );
2243 }
2244
2245 /**
2246 * Generate the navigation links when browsing through an article revisions
2247 * It shows the information as:
2248 * Revision as of <date>; view current revision
2249 * <- Previous version | Next Version ->
2250 *
2251 * @access private
2252 * @param string $oldid Revision ID of this article revision
2253 */
2254 function setOldSubtitle( $oldid=0 ) {
2255 global $wgLang, $wgOut, $wgUser;
2256
2257 $current = ( $oldid == $this->mLatest );
2258 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2259 $sk = $wgUser->getSkin();
2260 $lnk = $current
2261 ? wfMsg( 'currentrevisionlink' )
2262 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2263 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2264 $prevlink = $prev
2265 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2266 : wfMsg( 'previousrevision' );
2267 $nextlink = $current
2268 ? wfMsg( 'nextrevision' )
2269 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2270 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2271 $wgOut->setSubtitle( $r );
2272 }
2273
2274 /**
2275 * This function is called right before saving the wikitext,
2276 * so we can do things like signatures and links-in-context.
2277 *
2278 * @param string $text
2279 */
2280 function preSaveTransform( $text ) {
2281 global $wgParser, $wgUser;
2282 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2283 }
2284
2285 /* Caching functions */
2286
2287 /**
2288 * checkLastModified returns true if it has taken care of all
2289 * output to the client that is necessary for this request.
2290 * (that is, it has sent a cached version of the page)
2291 */
2292 function tryFileCache() {
2293 static $called = false;
2294 if( $called ) {
2295 wfDebug( " tryFileCache() -- called twice!?\n" );
2296 return;
2297 }
2298 $called = true;
2299 if($this->isFileCacheable()) {
2300 $touched = $this->mTouched;
2301 $cache = new CacheManager( $this->mTitle );
2302 if($cache->isFileCacheGood( $touched )) {
2303 wfDebug( " tryFileCache() - about to load\n" );
2304 $cache->loadFromFileCache();
2305 return true;
2306 } else {
2307 wfDebug( " tryFileCache() - starting buffer\n" );
2308 ob_start( array(&$cache, 'saveToFileCache' ) );
2309 }
2310 } else {
2311 wfDebug( " tryFileCache() - not cacheable\n" );
2312 }
2313 }
2314
2315 /**
2316 * Check if the page can be cached
2317 * @return bool
2318 */
2319 function isFileCacheable() {
2320 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2321 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2322
2323 return $wgUseFileCache
2324 and (!$wgShowIPinHeader)
2325 and ($this->getID() != 0)
2326 and ($wgUser->isAnon())
2327 and (!$wgUser->getNewtalk())
2328 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2329 and (empty( $action ) || $action == 'view')
2330 and (!isset($oldid))
2331 and (!isset($diff))
2332 and (!isset($redirect))
2333 and (!isset($printable))
2334 and (!$this->mRedirectedFrom);
2335 }
2336
2337 /**
2338 * Loads page_touched and returns a value indicating if it should be used
2339 *
2340 */
2341 function checkTouched() {
2342 $fname = 'Article::checkTouched';
2343 if( !$this->mDataLoaded ) {
2344 $dbr =& $this->getDB();
2345 $data = $this->pageDataFromId( $dbr, $this->getId() );
2346 if( $data ) {
2347 $this->loadPageData( $data );
2348 }
2349 }
2350 return !$this->mIsRedirect;
2351 }
2352
2353 /**
2354 * Get the page_touched field
2355 */
2356 function getTouched() {
2357 # Ensure that page data has been loaded
2358 if( !$this->mDataLoaded ) {
2359 $dbr =& $this->getDB();
2360 $data = $this->pageDataFromId( $dbr, $this->getId() );
2361 if( $data ) {
2362 $this->loadPageData( $data );
2363 }
2364 }
2365 return $this->mTouched;
2366 }
2367
2368 /**
2369 * Edit an article without doing all that other stuff
2370 * The article must already exist; link tables etc
2371 * are not updated, caches are not flushed.
2372 *
2373 * @param string $text text submitted
2374 * @param string $comment comment submitted
2375 * @param bool $minor whereas it's a minor modification
2376 */
2377 function quickEdit( $text, $comment = '', $minor = 0 ) {
2378 $fname = 'Article::quickEdit';
2379 wfProfileIn( $fname );
2380
2381 $dbw =& wfGetDB( DB_MASTER );
2382 $dbw->begin();
2383 $revision = new Revision( array(
2384 'page' => $this->getId(),
2385 'text' => $text,
2386 'comment' => $comment,
2387 'minor_edit' => $minor ? 1 : 0,
2388 ) );
2389 $revisionId = $revision->insertOn( $dbw );
2390 $this->updateRevisionOn( $dbw, $revision );
2391 $dbw->commit();
2392
2393 wfProfileOut( $fname );
2394 }
2395
2396 /**
2397 * Used to increment the view counter
2398 *
2399 * @static
2400 * @param integer $id article id
2401 */
2402 function incViewCount( $id ) {
2403 $id = intval( $id );
2404 global $wgHitcounterUpdateFreq;
2405
2406 $dbw =& wfGetDB( DB_MASTER );
2407 $pageTable = $dbw->tableName( 'page' );
2408 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2409 $acchitsTable = $dbw->tableName( 'acchits' );
2410
2411 if( $wgHitcounterUpdateFreq <= 1 ){ //
2412 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2413 return;
2414 }
2415
2416 # Not important enough to warrant an error page in case of failure
2417 $oldignore = $dbw->ignoreErrors( true );
2418
2419 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2420
2421 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2422 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2423 # Most of the time (or on SQL errors), skip row count check
2424 $dbw->ignoreErrors( $oldignore );
2425 return;
2426 }
2427
2428 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2429 $row = $dbw->fetchObject( $res );
2430 $rown = intval( $row->n );
2431 if( $rown >= $wgHitcounterUpdateFreq ){
2432 wfProfileIn( 'Article::incViewCount-collect' );
2433 $old_user_abort = ignore_user_abort( true );
2434
2435 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2436 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2437 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2438 'GROUP BY hc_id');
2439 $dbw->query("DELETE FROM $hitcounterTable");
2440 $dbw->query('UNLOCK TABLES');
2441 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2442 'WHERE page_id = hc_id');
2443 $dbw->query("DROP TABLE $acchitsTable");
2444
2445 ignore_user_abort( $old_user_abort );
2446 wfProfileOut( 'Article::incViewCount-collect' );
2447 }
2448 $dbw->ignoreErrors( $oldignore );
2449 }
2450
2451 /**#@+
2452 * The onArticle*() functions are supposed to be a kind of hooks
2453 * which should be called whenever any of the specified actions
2454 * are done.
2455 *
2456 * This is a good place to put code to clear caches, for instance.
2457 *
2458 * This is called on page move and undelete, as well as edit
2459 * @static
2460 * @param $title_obj a title object
2461 */
2462
2463 function onArticleCreate($title_obj) {
2464 global $wgUseSquid, $wgPostCommitUpdateList;
2465
2466 $title_obj->touchLinks();
2467 $titles = $title_obj->getLinksTo();
2468
2469 # Purge squid
2470 if ( $wgUseSquid ) {
2471 $urls = $title_obj->getSquidURLs();
2472 foreach ( $titles as $linkTitle ) {
2473 $urls[] = $linkTitle->getInternalURL();
2474 }
2475 $u = new SquidUpdate( $urls );
2476 array_push( $wgPostCommitUpdateList, $u );
2477 }
2478 }
2479
2480 function onArticleDelete( $title ) {
2481 global $wgMessageCache;
2482
2483 $title->touchLinks();
2484
2485 if( $title->getNamespace() == NS_MEDIAWIKI) {
2486 $wgMessageCache->replace( $title->getDBkey(), false );
2487 }
2488 }
2489
2490 /**
2491 * Purge caches on page update etc
2492 */
2493 function onArticleEdit( $title ) {
2494 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2495
2496 $urls = array();
2497
2498 // Template namespace? Purge all articles linking here.
2499 // FIXME: When a templatelinks table arrives, use it for all includes.
2500 if ( $title->getNamespace() == NS_TEMPLATE) {
2501 $titles = $title->getLinksTo();
2502 Title::touchArray( $titles );
2503 if ( $wgUseSquid ) {
2504 foreach ( $titles as $link ) {
2505 $urls[] = $link->getInternalURL();
2506 }
2507 }
2508 }
2509
2510 # Squid updates
2511 if ( $wgUseSquid ) {
2512 $urls = array_merge( $urls, $title->getSquidURLs() );
2513 $u = new SquidUpdate( $urls );
2514 array_push( $wgPostCommitUpdateList, $u );
2515 }
2516
2517 # File cache
2518 if ( $wgUseFileCache ) {
2519 $cm = new CacheManager( $title );
2520 @unlink( $cm->fileCacheName() );
2521 }
2522 }
2523
2524 /**#@-*/
2525
2526 /**
2527 * Info about this page
2528 * Called for ?action=info when $wgAllowPageInfo is on.
2529 *
2530 * @access public
2531 */
2532 function info() {
2533 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2534 $fname = 'Article::info';
2535
2536 if ( !$wgAllowPageInfo ) {
2537 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2538 return;
2539 }
2540
2541 $page = $this->mTitle->getSubjectPage();
2542
2543 $wgOut->setPagetitle( $page->getPrefixedText() );
2544 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2545
2546 # first, see if the page exists at all.
2547 $exists = $page->getArticleId() != 0;
2548 if( !$exists ) {
2549 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2550 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2551 } else {
2552 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2553 }
2554 } else {
2555 $dbr =& wfGetDB( DB_SLAVE );
2556 $wl_clause = array(
2557 'wl_title' => $page->getDBkey(),
2558 'wl_namespace' => $page->getNamespace() );
2559 $numwatchers = $dbr->selectField(
2560 'watchlist',
2561 'COUNT(*)',
2562 $wl_clause,
2563 $fname,
2564 $this->getSelectOptions() );
2565
2566 $pageInfo = $this->pageCountInfo( $page );
2567 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2568
2569 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2570 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2571 if( $talkInfo ) {
2572 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2573 }
2574 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2575 if( $talkInfo ) {
2576 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2577 }
2578 $wgOut->addHTML( '</ul>' );
2579
2580 }
2581 }
2582
2583 /**
2584 * Return the total number of edits and number of unique editors
2585 * on a given page. If page does not exist, returns false.
2586 *
2587 * @param Title $title
2588 * @return array
2589 * @access private
2590 */
2591 function pageCountInfo( $title ) {
2592 $id = $title->getArticleId();
2593 if( $id == 0 ) {
2594 return false;
2595 }
2596
2597 $dbr =& wfGetDB( DB_SLAVE );
2598
2599 $rev_clause = array( 'rev_page' => $id );
2600 $fname = 'Article::pageCountInfo';
2601
2602 $edits = $dbr->selectField(
2603 'revision',
2604 'COUNT(rev_page)',
2605 $rev_clause,
2606 $fname,
2607 $this->getSelectOptions() );
2608
2609 $authors = $dbr->selectField(
2610 'revision',
2611 'COUNT(DISTINCT rev_user_text)',
2612 $rev_clause,
2613 $fname,
2614 $this->getSelectOptions() );
2615
2616 return array( 'edits' => $edits, 'authors' => $authors );
2617 }
2618
2619 /**
2620 * Return a list of templates used by this article.
2621 * Uses the templatelinks table
2622 *
2623 * @return array Array of Title objects
2624 */
2625 function getUsedTemplates() {
2626 $result = array();
2627 $id = $this->mTitle->getArticleID();
2628
2629 $dbr =& wfGetDB( DB_SLAVE );
2630 $res = $dbr->select( array( 'templatelinks' ),
2631 array( 'tl_namespace', 'tl_title' ),
2632 array( 'tl_from' => $id ),
2633 'Article:getUsedTemplates' );
2634 if ( false !== $res ) {
2635 if ( $dbr->numRows( $res ) ) {
2636 while ( $row = $dbr->fetchObject( $res ) ) {
2637 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2638 }
2639 }
2640 }
2641 $dbr->freeResult( $res );
2642 return $result;
2643 }
2644 }
2645
2646 ?>